const echarts = require('echarts');
const { createCanvas } = require('canvas');
export async function POST(req) {
  // type代表图类型 1、柱状图 2、折线图 3、环形图 4、饼图 5、柱形图+折线图
  const { data, title, format, type, legendData } = await req.json();

  let option;

  // 柱状图
  if (type === '1') {
    const { xData, yData } = data;

    option = {
      color: ['#74A0FA'],
      title: {
        text: title,
      },
      legend: {
        data: legendData,
        show: legendData?.length > 0 ? true : false,
        type: 'plain',
        bottom: 'auto',
        width: 'auto',
        itemWidth: 14,
        itemHeight: 14,
      },
      xAxis: {
        type: 'category',
        data: xData,
        axisLabel: {
          color: '#333',
          fontSize: 12,
          interval: 0,
          overflow: 'truncate',
          ellipsis: '...',
        },
        axisLine: {
          lineStyle: {
            color: '#ccc',
          },
        },
      },
      yAxis: {
        type: 'value',
        show: true,
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          formatter: '{value}',
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
          },
          show: true,
        },
        splitNumber: 4,
      },
      series: [
        {
          barMaxWidth: 14,
          barMinHeight: 5,
          type: 'bar',
          data: yData,
          label: {
            show: true,
            position: 'top',
            labelSetting: { show: true, position: 'top', color: '#333333', fontSize: 12, fontFamily: 'DINAlternate-Bold' },
            formatter: params => {
              const index = params.dataIndex;
              if (data?.ratio?.length > 0) {
                return `${params.value}(${(data?.ratio[index] * 100).toFixed(1)}%)`
              } else {
                return `${params.value}`
              }
            }
          },
          itemStyle: {
            // 柱形图圆角，初始化效果
            borderRadius: [2, 2, 0, 0],
          },
        },
      ],
    };
  }

  // 折线图
  if (type === '2') {
    option = {
      title: {
        text: title,
      },
      xAxis: {
        type: 'category',
        data: data?.xData
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: data?.yData,
          type: 'line',
          label: {
            show: true,
            position: 'top',
            color: '#333',
            fontFamily: 'DINAlternate-Bold',
            fontSize: 12,
          },
        }
      ]
    };
  }

  // 环形图和饼图
  if (type === '3' || type === '4') {
    option = {
      title: {
        text: title,
        left: 'center'
      },
      legend: {
        top: '5%',
        left: 'center'
      },
      series: [
        {
          name: 'Access From',
          type: 'pie',
          radius: type === '3' ? ['40%', '70%'] : '50%',
          avoidLabelOverlap: true,
          label: {
            alignTo: 'edge',
            minMargin: 5,
            edgeDistance: 10,
            lineHeight: 15,
            show: true,
            formatter: function (params) {
              return `${params?.data?.value}(${params?.percent}%)`;
            },
            emphasis: {
              //文本样式
              show: true,   
              //展示
              textStyle: {
                fontSize: '12',
                fontWeight: '600',
                color: '#333',
                fontFamily: 'DINAlternate-Bold',
              }
            }
          },
          data: data,
        }
      ]
    };
  }


  let image;
  
  if (format === 'svg') {
    const chart = echarts.init(null, null, {
      renderer: 'svg',
      ssr: true,
      width: 400,
      height: 300,
    });

    chart.setOption(option);

    const buffer = Buffer.from(chart.renderToSVGString());
    image = `data:image/svg+xml;base64,${buffer.toString('base64')}`;
    
  } else {
    echarts.setCanvasCreator(() => {
      return createCanvas();
    });
    
    let canvas = createCanvas(800, 600);
  
    let chart = echarts.init(canvas);
  
    chart.setOption(option);
  
    const buffer = canvas.toBuffer('image/png');
  
    chart.dispose();
    chart = null;

    image = `data:image/png;base64,${buffer.toString('base64')}`;
  }

  return Response.json({
    image,
  }, {
    status: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    },
  });
}